package com.xinyi.shicihui.configuration;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * @author xinyi
 * @desc
 * @date 2022/1/23
 */
public class HeaderRequestInterceptor implements ClientHttpRequestInterceptor {
    public static final String APP_ID = "wxxcx";
    public static final String APP_KEY = "qIt2QmZDJBgDlPkt";

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        HttpHeaders headers = request.getHeaders();
        String uuid = UUID.randomUUID().toString();
        long currTime = System.currentTimeMillis()/1000;
//        String uuid = "9fd36db8-b221-dae4-d350-21908343883b";
//        long currTime = 1642931690;
        String requestUri = URLEncoder.encode(request.getURI().toString().toLowerCase(), "UTF-8");
        System.out.println(requestUri);
        String sign = APP_ID + request.getMethodValue() + requestUri + currTime + uuid;
        headers.add(HttpHeaders.AUTHORIZATION, "Hmac " + APP_ID + ":" + doEncrypt(sign) + ":" + uuid + ":" + currTime);
        headers.add(HttpHeaders.USER_AGENT,
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
        return execution.execute(request, body);
    }

    private String doEncrypt(String message) {
        try {
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new SecretKeySpec(APP_KEY.getBytes(), "HmacSHA256");
            sha256_HMAC.init(secretKey);
            return Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(message.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}

